'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/shujutj/pub/getShuJu 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		console.log('EVENT', event)
		const db = uniCloud.database();
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: "",
			// todayList: [],
			// sevenList:[],
			// fifveList: [],
			senvendays: [],
			shujukanban: []
		};
		let res1 = {
			code: 0,
			msg: "",
		}
		// 业务逻辑开始-----------------------------------------------------------
		const {
			m
		} = data

		let {
			todayStart,
			todayEnd,
			monthStart,
			lastMonthStart,
			lastMonthEnd
		} = vk.pubfn.getCommonTime(new Date());
		let {
			yesterdayStart,
			yesterdayEnd
		} = vk.pubfn.getCommonTime(new Date());

		let sevendayStart = vk.pubfn.getOffsetTime(todayStart, {
			day: 7,
			mode: "before", // after 之后 before 之前
		});

		let fifdayStart = vk.pubfn.getOffsetTime(todayStart, {
			day: 15,
			mode: "before", // after 之后 before 之前
		});

		console.log('55=>hang', sevendayStart);

		if (m === '今天') {
			res1.shujukanban = await getStatisticsData(todayStart, todayEnd)
		}
		if (m === '昨天') {
			res1.shujukanban = await getStatisticsData(yesterdayStart, yesterdayEnd)
		}
		if (m === '7天') {
			res1.shujukanban = await getStatisticsData(sevendayStart, yesterdayEnd)
		}
		if (m === '15天') {
			res1.shujukanban = await getStatisticsData(fifdayStart, yesterdayEnd)
		}
		if (m === '本月') {
			res1.shujukanban = await getStatisticsData(monthStart, yesterdayEnd)
		}
		if (m === '上月') {
			res1.shujukanban = await getStatisticsData(lastMonthStart, lastMonthEnd)
		}


		//前七天
		if (m === '1') {
			// res1.senvendays = await vk.baseDao.select({
			// 	dbName: "a_datas", // 表名
			// 	getCount: false, // 是否需要同时查询满足条件的记录总数量，默认false
			// 	getMain: false, // 是否只返回rows数据，默认false
			// 	pageIndex: 1, // 当前第几页
			// 	pageSize: 7, // 每页条数
			// 	whereJson: { // 条件
			// 		agent_id: userInfo.my_invite_code,
			// 		type: 1,
			// 	},
			// 	// 按_id降序 asc 升序 desc 降序 
			// 	sortArr: [{
			// 		name: "date_time ",
			// 		type: "desc"
			// 	}],
			// });
		}


		async function getStatisticsData(start, end) {
			//查询昨日新增用户数
			let agent_last_num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					invite_code: userInfo.my_invite_code,
					register_date: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询某段时间充值总金额（有新用户和老用户充值）
			let agent_last_jrczje = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: userInfo.my_invite_code,
					pay_status: 1,
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询昨日充值笔数
			let agent_last_jrczbs = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					invite_code: userInfo.my_invite_code,
					pay_status: 1,
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询昨日退款笔数
			let agent_last_cztkbs = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					invite_code: userInfo.my_invite_code,
					pay_status: 2,
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询昨日退款总金额
			let all_last_cztkje = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 2,
					// user_register_date: _.and(_.gt(last_StartTime), _.lt(last_EndTime)),
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询昨日新用户充值总金额
			let all_last_xyhczje = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					user_register_date: _.and(_.gt(start), _.lt(end)),
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});
			//查询昨日充值人数
			//查询一共有多少个符合条件的充值订单，条件为：已支付+记录时间为今天
			let agent_yesterdayRecharges = await vk.baseDao.select({
				dbName: "a_recharge", // 表名
				getCount: true, // 是否需要同时查询满足条件的记录总数量，默认false
				getMain: false, // 是否只返回rows数据，默认false
				pageIndex: 1, // 当前第几页
				pageSize: -1, // 每页条数
				// 只要user_id字段
				fieldJson: {
					user_id: true
				},
				whereJson: {
					invite_code: userInfo.my_invite_code,
					pay_status: 1,
					_add_time: _.and(_.gt(start), _.lt(end))
				}
			});

			//从数组中提取user_id字段形式新的数组
			let agent_rows1 = vk.pubfn.arrayObjectGetArray(agent_yesterdayRecharges.rows, "user_id");
			//一个用户可能充值多次，因此需要去重
			let agent_newRows1 = [...new Set(agent_rows1)]; //利用了Set结构不能接收重复数据的特点进行去重
			let agent_last_jrczrs = agent_newRows1.length; //查询昨日充值人数


			//昨日充值率
			let zrczl = agent_last_jrczrs / agent_last_num || 0;
			zrczl = vk.pubfn.toDecimal(zrczl, 4);

			//人均充值金额=昨日充值金额/昨日充值人数
			let rjczzje = (agent_last_jrczje / 100) / agent_last_jrczrs || 0;
			rjczzje = vk.pubfn.toDecimal(rjczzje, 2);

			//人均充值笔数
			let rjczzbs = agent_last_jrczbs / agent_last_jrczrs || 0;
			rjczzbs = vk.pubfn.toDecimal(rjczzbs, 2);


			console.log("zrczl=", vk.pubfn.percentageFilter(zrczl, true, 0));
			console.log("206");
			res.shujukanban = [{
					id: '1',
					title: '新增人数（人）',
					center: agent_last_num
				},
				{
					id: '2',
					title: '充值金额（元）',
					center: agent_last_jrczje / 100
				},
				{
					id: '3',
					title: '充值笔数',
					center: agent_last_jrczbs
				},
				{
					id: '4',
					title: '充值人数',
					center: agent_last_jrczrs
				},
				{
					id: '5',
					title: '充值率',
					center: vk.pubfn.percentageFilter(zrczl, true, 0)
				},
				{
					id: '6',
					title: '人均充值金额',
					center: rjczzje.toFixed(2)
				},
				{
					id: '7',
					title: '退款笔数',
					center: agent_last_cztkbs
				},
				{
					id: '8',
					title: '退款金额（元）',
					center: all_last_cztkje / 100
				},
				{
					id: '9',
					title: '人均充值笔数',
					center: rjczzbs.toFixed(2)
				}
			]

			// console.log('kkkkkkkkkkkkk',res.shujukanban);
			return res.shujukanban
		}


		console.log('昨日数据统计', res1.shujukanban)

		// 业务逻辑结束-----------------------------------------------------------
		return res1;
	}
}
